package bfs;

import model.TreeNode;

import java.util.*;

public class App {
    public static void main(String[] args) {
        //    10
        // 1     20
        //2 3  22  23
        TreeNode root = new TreeNode(10);
        root.left = new TreeNode(1);
        root.right = new TreeNode(20);

        root.left.left = new TreeNode(2);
        root.left.right = new TreeNode(3);

        root.right.left = new TreeNode(22);
        root.right.right = new TreeNode(23);

        List<List<TreeNode>> res = new App().bfs(root);
        for (int i = 0; i < res.size(); i++) {
            String str = "第" + i + "层：";
            for (int j = 0; j < res.get(i).size(); j++) {
                str += res.get(i).get(j).val + ",";
            }
            System.out.println(str);
        }
    }

    public List<List<TreeNode>> bfs(TreeNode root) {
        List<List<TreeNode>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<TreeNode> results = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode curr = queue.poll();
//                System.out.println(curr.val);
                results.add(curr);
                if (curr.left != null) {
                    queue.offer(curr.left);
                }
                if (curr.right != null) {
                    queue.offer(curr.right);
                }

            }
            res.add(results);
        }
        return res;
    }
}
